package com.base.cn.platform.os.service.user.member;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.user.member.CusUserMemberBuyRecordDao;
import com.base.cn.platform.os.entity.user.member.CusUserMemberBuyRecord;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.entity.user.user.UserCondition;
import com.base.cn.platform.os.service.manage.config.SysConfigBiz;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户会员记录Biz
 * @author ll
 * @create 2018-04-26
 */
@Service
public class CusUserMemberBuyRecordBiz extends BaseBiz<CusUserMemberBuyRecord,CusUserMemberBuyRecordDao> {

    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private SysConfigBiz sysConfigBiz;

    /**
     * 检测用户是否购买过会员
     * @param userId 用户ID
     * @return true购买过，false未购买过
     */
    public boolean checkUserBuyMember(BigDecimal userId){
        if(DataUtil.idIsNotNull(userId)){
            //查询会员开通记录
            CusUserMemberBuyRecord record = queryUserBuyMemberRecord(userId);
            if(ObjectUtils.isNotEmpty(record)){
                return true;
            }
        }
        return false;
    }

    /**
     * 检测用户是否有会员权限
     * @param userId 用户ID
     * @return true 有，false 没有
     */
    public boolean checkUserUseMemberPrice(BigDecimal userId){
        if(DataUtil.idIsNotNull(userId)){
            TreeMap<String, String> configMap = sysConfigBiz.getSysConfigContext(ConfigName.SALE);
            int selaSwitch = Integer.parseInt(configMap.get("selaSwitch"));
            if(selaSwitch==2 || selaSwitch==3){
                String time = DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
                CusUserMemberBuyRecord record = this.findOne(" userId="+userId+" and status=1  and endTime> '"+time+"' and beginTime < '"+time+"' ",null);
                if(ObjectUtils.isNotEmpty(record)){
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 添加会员购买与你
     * @param userId 用户ID
     * @param day 购买会员天数
     */
    public void addUserMemberBuyRecord(BigDecimal userId,int day){
        CusUserMemberBuyRecord record = this.queryUserBuyMemberRecord(userId);
        if(ObjectUtils.isNotEmpty(record)){//购买过会员，修改会员的过期时间

            if(record.getEndTime().after(new Date())){
                record.setEndTime( DateUtils.addByDate(record.getEndTime(), Calendar.DAY_OF_MONTH, day));
            }else{
                record.setEndTime( DateUtils.addByDate(new Date(), Calendar.DAY_OF_MONTH, day));
            }

            record.setUpdateTime(new Date());
            this.updateById(record,null);
        }else{//未购买过会员，创建会员购买记录
            Date createTime = new Date();
            CusUserMemberBuyRecord memberBuyRecord = new CusUserMemberBuyRecord();
            memberBuyRecord.setBeginTime(createTime);
            memberBuyRecord.setStatus(1);
            memberBuyRecord.setEndTime(createTime);
            memberBuyRecord.setUserId(userId);
            Date endTime = DateUtils.addByDate(memberBuyRecord.getEndTime(),Calendar.DAY_OF_MONTH, day);
            memberBuyRecord.setEndTime(endTime);
            this.save(memberBuyRecord);
        }
    }

    /**
     * 修改会员有效时间 (用于退费)
     * @param userId 用户ID
     * @param day 更新天数（正数是加，负数是减）
     */
    public void updateMemberBuyRecordValidTime(BigDecimal userId,int day){
        CusUserMemberBuyRecord cusUserMemberBuyRecord =new CusUserMemberBuyRecord();
        cusUserMemberBuyRecord.setUserId(userId);
        CusUserMemberBuyRecord userMemberBuyRecord = this.findOne(whereSql(cusUserMemberBuyRecord),null);
        if(ObjectUtils.isNotEmpty(userMemberBuyRecord)){
            Date endTime = DateUtils.addByDate(userMemberBuyRecord.getEndTime(), Calendar.DAY_OF_MONTH,day);
            userMemberBuyRecord.setEndTime(endTime);
            this.updateById(userMemberBuyRecord,null);
        }
    }

    /**
     * 获取用户开通的会员记录
     * @param userId 用户ID
     * @return UserMemberBuyRecord
     */
    public CusUserMemberBuyRecord queryUserBuyMemberRecord(BigDecimal userId){
        if(DataUtil.idIsNotNull(userId)){
            CusUserMemberBuyRecord userMemberBuyRecord = new CusUserMemberBuyRecord();
            userMemberBuyRecord.setUserId(userId);
            userMemberBuyRecord.setStatus(1);
            String where =whereSql(userMemberBuyRecord);
            CusUserMemberBuyRecord  record =this.findOne(where,null);
            if(ObjectUtils.isNotEmpty(record)){
                int validDay = DateUtils.daysBeforeNow(record.getEndTime());
                record.setValidDay(validDay);
                return record;
            }
        }
        return null;
    }


    /**
     * 获取用户开通的会员记录
     * @param userIds 用户IDs
     * @return UserMemberBuyRecord
     */
    public List<CusUserMemberBuyRecord> queryUserBuyMemberRecordByUserIds(String userIds){
        if(StringUtils.isNotEmpty(userIds)){
            CusUserMemberBuyRecord userMemberBuyRecord = new CusUserMemberBuyRecord();
            userMemberBuyRecord.setUserIds(userIds);
            userMemberBuyRecord.setStatus(1);
            String where =whereSql(userMemberBuyRecord);
            List<CusUserMemberBuyRecord>  record =this.find(where,null,null);
            if(ObjectUtils.isNotEmpty(record)){
                for (CusUserMemberBuyRecord buyRecord: record){
                    int validDay = DateUtils.daysBeforeNow(buyRecord.getEndTime());
                    buyRecord.setValidDay(validDay);
                }
                return record;
            }
        }
        return null;
    }

    /**
     * 查询会员购买记录
     * @param userMemberBuyRecord 查询条件
     * @param page 分页条件
     * @return
     */
    public PageInfo<CusUserMemberBuyRecord> queryUserMemberBuyRecordList(CusUserMemberBuyRecord userMemberBuyRecord, Pagination page,boolean userData){
        List<CusUser> userList=null;
        PageInfo<CusUserMemberBuyRecord> userMemberBuyRecordPageInfo=new PageInfo<>();
        if(ObjectUtils.isNotEmpty(userMemberBuyRecord)){
            if(StringUtils.isNotEmpty(userMemberBuyRecord.getKeyWord())){
                String k = userMemberBuyRecord.getKeyWord().trim();
                UserCondition userContainColumns = new UserCondition();
                userContainColumns.setKeyWord(k);
                userList  = cusUserBiz.queryUserList(userContainColumns,null,new ArrayList<>(),
                        false,false,false,
                        false,false,false,false);
                if(ObjectUtils.isEmpty(userList)){
                    return userMemberBuyRecordPageInfo;
                }
                String userIds = userList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
                userMemberBuyRecord.setUserIds(userIds);
            }
        }
        String whereSql = whereSql(userMemberBuyRecord);
        userMemberBuyRecordPageInfo =this.findPage(whereSql,page,null);
        //设置会员的用户数据
        this.setUserMemberBuyRecordUser(userMemberBuyRecordPageInfo.getList(),userList,userData);
        return  userMemberBuyRecordPageInfo;
    }

    //====================================================

    /**
     * 设置会员购买记录的用户数据
     * @param memberBuyRecordList
     * @param userList
     * @param userData
     */
    private void setUserMemberBuyRecordUser(List<CusUserMemberBuyRecord> memberBuyRecordList, List<CusUser> userList,boolean userData){
        if(ObjectUtils.isNotEmpty(memberBuyRecordList) && userData){
            if(ObjectUtils.isNotEmpty(userList)){
                setBuyRecordUser(memberBuyRecordList,userList);
            }else{
                this.setUserMemberBuyRecordUser(memberBuyRecordList);
            }
        }
    }

    /**
     * 设置用户数据
     * @param userMemberBuyRecordList
     */
    private void setUserMemberBuyRecordUser(List<CusUserMemberBuyRecord> userMemberBuyRecordList){
        if(ObjectUtils.isNotEmpty(userMemberBuyRecordList)){
            String userIds = userMemberBuyRecordList.stream().map(e->e.getUserId().toString()).distinct().collect(Collectors.joining(","));
            if(StringUtils.isNotEmpty(userIds)){
                List<CusUser> userList = cusUserBiz.queryUserByIds(userIds,false,false,false,false,false,false,false);
                setBuyRecordUser(userMemberBuyRecordList,userList);
            }
        }
    }

    /**
     * 设置会员购买记录的用户信息
     * @param userMemberBuyRecordList
     * @param userList
     */
    private void setBuyRecordUser(List<CusUserMemberBuyRecord> userMemberBuyRecordList,List<CusUser> userList){
        if(ObjectUtils.isNotEmpty(userMemberBuyRecordList) && ObjectUtils.isNotEmpty(userList)){
            Map<BigDecimal,CusUser> userMap = userList.stream().collect(Collectors.toMap(CusUser::getId, e->e));
            for(CusUserMemberBuyRecord userMemberBuyRecord : userMemberBuyRecordList ){
                CusUser user = userMap.get(userMemberBuyRecord.getUserId());
                userMemberBuyRecord.setUser(user);
            }
        }
    }

    public String whereSql(CusUserMemberBuyRecord cusUserMemberBuyRecord){
        StringBuilder where = new StringBuilder(" 1=1 ");
        if(ObjectUtils.isNotEmpty(cusUserMemberBuyRecord)){
            if (DataUtil.idIsNotNull(cusUserMemberBuyRecord.getUserId())){
                where .append(" and userId = ").append(cusUserMemberBuyRecord.getUserId());
            }
            if (ObjectUtils.isNotEmpty(cusUserMemberBuyRecord.getBeginTime())){
                where .append(" and beginTime <= '").append(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss")).append("' ");
            }
            if (ObjectUtils.isNotEmpty(cusUserMemberBuyRecord.getEndTime())){
                where .append(" and endTime >= '").append( DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss")).append("' ");
            }
            if (StringUtils.isNotEmpty(cusUserMemberBuyRecord.getUserIds())){
                where .append(" and userId in (").append(cusUserMemberBuyRecord.getUserIds()).append(")");
            }
            if(cusUserMemberBuyRecord.getStatus()!=null&&cusUserMemberBuyRecord.getStatus()>0){
                where .append( " and status =").append(cusUserMemberBuyRecord.getStatus());
            }
        }
        where .append( " order by createTime desc");
        return where.toString();
    }

}
